import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/notice.dart';
import 'package:kxy_flutter_app/services/integral_service.dart';

class NoticeDetailView extends StatefulWidget {
  final String noticeId;
  NoticeDetailView({
    Key key,
    @required this.noticeId,
  }) : super(key: key);

  @override
  _NoticeDetailViewState createState() => _NoticeDetailViewState();
}

class _NoticeDetailViewState extends State<NoticeDetailView> {
  Future loadFuture;
  NoticeDetail notice;

  @override
  void initState() {
    loadFuture = loadNotice();
    IntegralService.addNotice(widget.noticeId);
    super.initState();
  }

  Future loadNotice() async {
    var res = await Http.instance.post('/news-app/notice/info', params: {
      'id': widget.noticeId,
    });

    if (res.code == 200) {
      notice = NoticeDetail.fromJson(res.data);
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }

    await Http.instance.post('/news-app/notice/savehistory', params: {
      'userId': Auth.instance.userId,
      'noticeId': widget.noticeId,
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('消息通知')),
      backgroundColor: Colors.white,
      body: FutureBuilder(
        future: loadFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          title,
          subtitle,
          noticeBody,
        ],
      ),
    );
  }

  Widget get title {
    return Text(
      notice.title,
      style: TextStyle(
        fontSize: 20,
        color: Colors.black87,
      ),
    );
  }

  Widget get subtitle {
    var format = new DateFormat('yyyy-MM-dd');
    return Padding(
      padding: EdgeInsets.only(top: 10),
      child: Text(
        '发布时间: ${format.format(notice.createTime)}',
        style: TextStyle(
          fontSize: 13,
          color: Colors.black54,
        ),
      ),
    );
  }

  Widget get noticeBody {
    return HtmlWidget(
      notice.content,
      textStyle: TextStyle(
        fontSize: 16,
        color: Colors.black,
        height: 1.6,
        letterSpacing: 0.2,
      ),
    );
  }
}
